import React, { useEffect, useState, useRef } from 'react';
import { View, Text, StyleSheet, SafeAreaView, FlatList, Image, TextInput, TouchableOpacity, Modal, Animated, ScrollView, ActivityIndicator, RefreshControl, Dimensions } from 'react-native';
import Header from '../../../components/Header';
import { getDeviceMaintainRecord, getAllRoomApi } from './api';
import CustomQRScanner from '../../../components/CustomQRScanner';
import PortalDropdown from '../../../components/PortalDropdown';
import saoma from '../../../assets/saoma.png';
import xiala from '../../../assets/xiala.png';
const MAINTAIN_STATE_MAP: { [key: number]: string } = {
    1: '待保养',
    2: '待复核',
    3: '已复核',
};

const MAINTAIN_STATE_OPTIONS = [
    { value: 1, label: '待保养' },
    { value: 2, label: '待复核' },
    { value: 3, label: '已复核' },
];

interface DeviceMaintainProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
    onNavigateToScreen?: (route: string) => void;
}

const DeviceMaintain: React.FC<DeviceMaintainProps> = ({ onNavigateToLogin, onBackPress, onNavigateToScreen }) => {
    const [maintainList, setMaintainList] = useState<any[]>([]);
    const [search, setSearch] = useState('');
    const [scanVisible, setScanVisible] = useState(false);
    const [stateDropdownVisible, setStateDropdownVisible] = useState(false);
    const [selectedStates, setSelectedStates] = useState<number[]>([]);
    const [loading, setLoading] = useState(false);
    const [arrowRotation] = useState(new Animated.Value(0));
    const [roomArrowRotation] = useState(new Animated.Value(0));
    const [roomDropdownVisible, setRoomDropdownVisible] = useState(false);
    const [roomList, setRoomList] = useState<any[]>([]);
    const [selectedRooms, setSelectedRooms] = useState<string[]>([]);

    // 分页相关状态
    const [current, setCurrent] = useState(1);
    const [size] = useState(10);
    const [hasMore, setHasMore] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    // Portal 下拉框的 ref
    const roomTriggerRef = useRef<View>(null);
    const stateTriggerRef = useRef<View>(null);

    // 搜索保养任务
    const searchMaintainTasks = async (
        keyword: string = search,
        stateList: number[] = selectedStates,
        roomIdList: string[] = selectedRooms,
        isLoadMore: boolean = false
    ) => {
        if (isLoadMore) {
            setLoadingMore(true);
        } else {
            setLoading(true);
            setCurrent(1);
            setHasMore(true);
        }

        try {
            const result = await getDeviceMaintainRecord({
                current: isLoadMore ? current + 1 : 1,
                size,
                room_id_list: roomIdList,
                state_list: stateList,
                keyword: keyword,
            });

            const newRecords = result?.data?.records || [];
            const total = result?.data?.total || 0;

            if (isLoadMore) {
                setMaintainList((prev: any[]) => [...prev, ...newRecords]);
                setCurrent((prev: number) => prev + 1);
            } else {
                setMaintainList(newRecords);
                setCurrent(1);
            }

            // 判断是否还有更多数据
            const totalLoaded = isLoadMore ? maintainList.length + newRecords.length : newRecords.length;
            setHasMore(totalLoaded < total);

        } catch (error) {
            if (!isLoadMore) {
                setMaintainList([]);
            }
        } finally {
            if (isLoadMore) {
                setLoadingMore(false);
            } else {
                setLoading(false);
            }
        }
    };

    // 初始加载
    useEffect(() => {
        searchMaintainTasks('', selectedStates, selectedRooms, false);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 车间下拉数据
    useEffect(() => {
        getAllRoomApi().then(res => {
            setRoomList(res?.data || []);
        });
    }, []);

    // 滑动到底部加载更多
    const handleLoadMore = () => {
        if (hasMore && !loadingMore && !loading) {
            searchMaintainTasks(search, selectedStates, selectedRooms, true);
        }
    };

    // 下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true);
        await searchMaintainTasks(search, selectedStates, selectedRooms, false);
        setRefreshing(false);
    };

    // 输入关键词立即搜索
    const handleSearchChange = (text: string) => {
        setSearch(text);
        clearTimeout((global as any).searchTimeout);
        (global as any).searchTimeout = setTimeout(() => {
            searchMaintainTasks(text, selectedStates, selectedRooms, false);
        }, 500);
    };

    // 扫码处理
    const onScanPress = () => {
        setScanVisible(true);
    };

    const onBarcodeScan = (data: string) => {
        setScanVisible(false);
        setSearch(data);
        // 扫码后立即搜索
        searchMaintainTasks(data, selectedStates, selectedRooms, false);
    };

    // 状态选择处理
    const handleStateToggle = (stateValue: number) => {
        setSelectedStates((prev: number[]) => {
            const newStates = prev.includes(stateValue)
                ? prev.filter((s: number) => s !== stateValue)
                : [...prev, stateValue];

            // 状态改变后立即搜索
            setTimeout(() => {
                searchMaintainTasks(search, newStates, selectedRooms, false);
            }, 100);
            return newStates;
        });
    };

    // 车间选择处理
    const handleRoomToggle = (roomId: string) => {
        setSelectedRooms((prev: string[]) => {
            const newRooms = prev.includes(roomId)
                ? prev.filter((id: string) => id !== roomId)
                : [...prev, roomId];
            setTimeout(() => {
                searchMaintainTasks(search, selectedStates, newRooms, false);
            }, 100);
            return newRooms;
        });
    };

    // 切换下拉框显示状态
    const toggleStateDropdown = () => {
        const toValue = stateDropdownVisible ? 0 : 1;
        setStateDropdownVisible(!stateDropdownVisible);

        Animated.timing(arrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 切换车间下拉框显示状态
    const toggleRoomDropdown = () => {
        const toValue = roomDropdownVisible ? 0 : 1;
        setRoomDropdownVisible(!roomDropdownVisible);

        Animated.timing(roomArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };

    // 获取状态显示文本
    const getStateDisplayText = () => {
        if (selectedStates.length === 0) return '状态';
        if (selectedStates.length === 1) {
            const state = MAINTAIN_STATE_MAP[selectedStates[0]];
            return state;
        }
        return `已选${selectedStates.length}项`;
    };

    // 车间下拉显示文本
    const getRoomDisplayText = () => {
        if (selectedRooms.length === 0) return '车间';
        if (selectedRooms.length === 1) {
            const room = roomList.find((r: any) => r.id === selectedRooms[0]);
            return room ? `${room.dept_name}` : '车间';
        }
        return `已选${selectedRooms.length}项`;
    };

    // 获取状态按钮样式
    const getStatusButtonStyle = (state: number) => {
        switch (state) {
            case 1: // 待保养 - 红色
                return { ...styles.statusButton, borderColor: '#ff4444' };
            case 2: // 待复核 - 橙色
                return { ...styles.statusButton, borderColor: '#ffaa00' };
            case 3: // 已复核 - 绿色
                return { ...styles.statusButton, borderColor: '#00aa00' };
            default:
                return { ...styles.statusButton, borderColor: '#ff4444' };
        }
    };

    // 获取状态文本样式
    const getStatusTextStyle = (state: number) => {
        switch (state) {
            case 1: // 待保养 - 红色
                return { ...styles.statusText, color: '#ff4444' };
            case 2: // 待复核 - 橙色
                return { ...styles.statusText, color: '#ffaa00' };
            case 3: // 已复核 - 绿色
                return { ...styles.statusText, color: '#00aa00' };
            default:
                return { ...styles.statusText, color: '#ff4444' };
        }
    };

    // 保养任务卡片渲染
    const renderItem = ({ item }: { item: any }) => (
        <View style={styles.card}>
            <View style={styles.cardHeader}>
                <View style={styles.deviceInfo}>
                    <TouchableOpacity
                        style={styles.imageContainer}
                        onPress={() => {
                            setSelectedImage(item.device_link ? String(item.device_link) : '');
                            setImageModalVisible(true);
                        }}
                    >
                        <Image
                            source={item.device_link ? { uri: String(item.device_link) } : require('../../../assets/zwtp.png')}
                            style={styles.deviceImg}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                    <Text style={styles.deviceNum}>{item.device_num}</Text>
                </View>
                <View style={getStatusButtonStyle(item.state)}>
                    <Text style={getStatusTextStyle(item.state)}>{MAINTAIN_STATE_MAP[item.state] || '未知'}</Text>
                </View>
            </View>
            <View style={styles.cardDetails}>
                <View style={styles.detailRowGroup}>
                    <View style={styles.detailItemVertical}>
                        <Text style={styles.detailLabel}>计划时间</Text>
                        <Text style={styles.detailValue}>{item.plan_day || '无'}</Text>
                    </View>
                    <View style={styles.detailItemVertical1}>
                        <Text style={styles.detailLabel}>计划类型</Text>
                        <Text style={styles.detailValue}>{item.cycle_name || '无'}</Text>
                    </View>
                </View>
            </View>
            <View style={styles.planNumberContainer}>
                <Text style={styles.detailLabel}>计划单号</Text>
                <Text style={styles.detailValue}>{item.plan_num || '无'}</Text>
            </View>
            <TouchableOpacity
                style={styles.cardOverlay}
                activeOpacity={0.8}
                onPress={() => {
                    // 设置全局plan_id并跳转到详情页面
                    (global as any).maintainDetailPlanId = item.id;
                    if (onNavigateToScreen) {
                        onNavigateToScreen('Device/DeviceMaintain/DeviceMaintainDetail');
                    }
                }}
            />
        </View>
    );

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="保养任务"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            {/* 顶部搜索和筛选区 */}
            <View style={styles.topBar}>
                <View style={styles.inputContainer}>
                    <TextInput
                        style={styles.searchInput}
                        placeholder="请输入设备名称或编号搜索"
                        placeholderTextColor="#999"
                        value={search}
                        onChangeText={handleSearchChange}
                    />
                    {search.length > 0 && (
                        <TouchableOpacity
                            style={styles.clearButton}
                            onPress={() => {
                                setSearch('');
                                searchMaintainTasks('', selectedStates, selectedRooms, false);
                            }}
                        >
                            <Text style={styles.clearButtonText}>×</Text>
                        </TouchableOpacity>
                    )}
                </View>
                <TouchableOpacity style={styles.scanBtn} onPress={onScanPress}>
                    <Image source={saoma} style={{ width: 30, height: 30 }} />
                </TouchableOpacity>
            </View>
            <View style={styles.filterBar}>
                <View style={styles.stateDropdownContainer}>
                    <TouchableOpacity
                        ref={roomTriggerRef}
                        style={[styles.filterBtn, { marginHorizontal: 0 }]}
                        onPress={toggleRoomDropdown}
                    >
                        <Text style={{ color: '#333', fontSize: 16 }}>{getRoomDisplayText()}</Text>
                        <Animated.Image
                            source={xiala}
                            style={[
                                styles.arrowIcon,
                                {
                                    transform: [{
                                        rotate: roomArrowRotation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ['0deg', '180deg']
                                        })
                                    }]
                                }
                            ]}
                        />
                    </TouchableOpacity>
                    <PortalDropdown
                        visible={roomDropdownVisible}
                        onClose={() => {
                            setRoomDropdownVisible(false);
                            // 关闭时重置动画
                            Animated.timing(roomArrowRotation, {
                                toValue: 0,
                                duration: 200,
                                useNativeDriver: true,
                            }).start();
                        }}
                        options={roomList.map(room => ({ value: room.id, label: room.dept_name }))}
                        selectedValues={selectedRooms}
                        onSelect={handleRoomToggle}
                        triggerRef={roomTriggerRef}
                        placeholder="车间"
                        multiple={true}
                    />
                </View>
                <View style={styles.stateDropdownContainer}>
                    <TouchableOpacity
                        ref={stateTriggerRef}
                        style={[styles.filterBtn1, { marginHorizontal: 0 }]}
                        onPress={toggleStateDropdown}
                    >
                        <Text style={{ color: '#333', fontSize: 16 }}>{getStateDisplayText()}</Text>
                        <Animated.Image
                            source={xiala}
                            style={[
                                styles.arrowIcon,
                                {
                                    transform: [{
                                        rotate: arrowRotation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ['0deg', '180deg']
                                        })
                                    }]
                                }
                            ]}
                        />
                    </TouchableOpacity>
                    <PortalDropdown
                        visible={stateDropdownVisible}
                        onClose={() => {
                            setStateDropdownVisible(false);
                            // 关闭时重置动画
                            Animated.timing(arrowRotation, {
                                toValue: 0,
                                duration: 200,
                                useNativeDriver: true,
                            }).start();
                        }}
                        options={MAINTAIN_STATE_OPTIONS}
                        selectedValues={selectedStates}
                        onSelect={handleStateToggle}
                        triggerRef={stateTriggerRef}
                        placeholder="状态"
                        multiple={true}
                    />
                </View>
            </View>

            {/* 列表区域 */}
            {loading ? (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                    <Text style={styles.loadingText}>搜索中...</Text>
                </View>
            ) : (
                <FlatList
                    data={maintainList}
                    keyExtractor={(item, index) => `${item.id}_${index}`}
                    renderItem={renderItem}
                    contentContainerStyle={{ padding: 10 }}
                    onEndReached={handleLoadMore}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            onRefresh={handleRefresh}
                            colors={['#0076ff']}
                            tintColor="#0076ff"
                        />
                    }
                    ListEmptyComponent={
                        <View style={styles.emptyContainer}>
                            <Image
                                source={require('../../../assets/zwsj.png')}
                                style={styles.emptyImage}
                                resizeMode="contain"
                            />
                            <Text style={styles.emptyText}>暂无保养任务</Text>
                        </View>
                    }
                    ListFooterComponent={
                        loadingMore ? (
                            <View style={styles.loadingMoreContainer}>
                                <ActivityIndicator size="small" color="#0076ff" />
                                <Text style={styles.loadingMoreText}>加载更多...</Text>
                            </View>
                        ) : null
                    }
                />
            )}

            {/* 扫码模态框 */}
            <Modal visible={scanVisible} animationType="slide">
                <CustomQRScanner
                    onRead={onBarcodeScan}
                    onClose={() => setScanVisible(false)}
                />
            </Modal>

            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../assets/zwtp.png')}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    topBar: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        paddingTop: 10,
    },
    filterBar: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingHorizontal: 10,
        marginTop: 10,
        marginBottom: 24,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        position: 'relative',
    },
    searchInput: {
        flex: 1,
        height: 40,
        backgroundColor: '#fff',
        borderRadius: 17,
        paddingHorizontal: 16,
        paddingRight: 40,
        paddingVertical: 8,
        fontSize: 15,
        marginRight: 10,
    },
    clearButton: {
        position: 'absolute',
        right: 10,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
        alignItems: 'center',
        width: 30,
        height: 30,
    },
    clearButtonText: {
        color: '#999',
        fontSize: 16,
        fontWeight: 'bold',
        textAlign: 'center',
        textAlignVertical: 'center',
        lineHeight: 40,
        includeFontPadding: false,
        paddingTop: 0,
        paddingBottom: 0,
    },
    scanBtn: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#eee',
    },
    filterBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        flex: 1,
        backgroundColor: '#fff',
        marginRight: 2,
        borderRadius: 17,
        paddingVertical: 8,
        paddingHorizontal: 12,
        borderWidth: 1,
        borderColor: '#eee',
        minHeight: 36,
    },
    filterBtn1: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        flex: 1,
        marginLeft: 2,
        backgroundColor: '#fff',
        borderRadius: 17,
        paddingVertical: 8,
        paddingHorizontal: 12,
        borderWidth: 1,
        borderColor: '#eee',
        minHeight: 36,
    },
    stateDropdownContainer: {
        position: 'relative',
        flex: 1,
    },
    dropdownMenu: {
        position: 'absolute',
        top: 35,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#ddd',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.15,
        shadowRadius: 6,
        elevation: 4,
        zIndex: 1000,
        maxHeight: 200,
    },
    dropdownOption: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 12,
        paddingHorizontal: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    dropdownOptionSelected: {
        // 不要背景色和边框
    },
    dropdownOptionText: {
        fontSize: 16,
        color: '#333',
    },
    dropdownOptionTextSelected: {
        color: '#0076ff',
        fontWeight: 'bold',
    },
    checkmark: {
        fontSize: 20,
        color: '#0076ff',
        textAlignVertical: 'center',
        includeFontPadding: false,
    },
    arrowIcon: {
        width: 16,
        height: 16,
        marginLeft: 5,
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    cardHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 8,
    },
    deviceInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    deviceImg: {
        width: 50,
        height: 50,
        borderRadius: 6,
        backgroundColor: '#eee',
        marginRight: 12,
    },
    deviceNum: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222',
    },
    statusButton: {
        backgroundColor: '#fff',
        borderRadius: 4,
        paddingVertical: 6,
        paddingHorizontal: 12,
        borderWidth: 1,
    },
    statusText: {
        fontSize: 12,
        color: '#ff4444',
        fontWeight: 'bold',
    },
    cardDetails: {
        marginTop: 8,
        backgroundColor: '#f8f8f8',
        borderRadius: 8,
        padding: 12,
        paddingHorizontal: 15,
    },
    detailRowGroup: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 6,
        paddingHorizontal: 0,
    },
    detailItemVertical: {
        flex: 0,
        width: '24%',
    },
    detailItemVertical1: {
        flex: 0,
        width: '20%',
    },
    detailLabel: {
        fontSize: 13,
        color: '#666',
        marginBottom: 4,
    },
    detailValue: {
        fontSize: 12,
        color: '#333',
        textAlign: 'left',
    },
    planNumberContainer: {
        marginTop: 8,
        backgroundColor: '#f8f8f8',
        borderRadius: 8,
        padding: 12,
        paddingHorizontal: 15,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#666',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    emptyImage: {
        width: 200,
        height: 200,
        marginBottom: 16,
    },
    emptyText: {
        fontSize: 16,
        color: '#999',
    },
    loadingMoreContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 15,
    },
    loadingMoreText: {
        marginLeft: 8,
        fontSize: 14,
        color: '#666',
    },
    cardOverlay: {
        position: 'absolute',
        top: 0,
        left: 70, // 图片宽度 + marginRight
        right: 0,
        bottom: 0,
        backgroundColor: 'transparent',
    },
    imageContainer: {
        position: 'relative',
        zIndex: 10,
    },
    imageModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    imageModalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
    },
    fullScreenImage: {
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height,
    },
});

export default DeviceMaintain; 